// 引入ws模块
const WebSocket = require('ws');

// 创建一个WebSocket服务器实例，监听8080端口
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
    console.log('Client connected');

    // 当接收到来自客户端的消息时
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);

        // 发送消息回客户端
        ws.send(`Hello from server! You sent: ${message}`);
    });

    // 当WebSocket连接关闭时
    ws.on('close', function close() {
        console.log('Client disconnected');
    });

    // 发送一个欢迎消息给客户端
    ws.send('Welcome to the WebSocket server!');
});

console.log('WebSocket server listening on port 8080');
